package com.lesent.kafka.service.impl;

import com.lesent.kafka.common.JsonHelper;
import com.lesent.kafka.model.KafkaNode;
import com.lesent.kafka.model.Student;
import com.lesent.kafka.service.IZookeeperService;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.data.Stat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * @author shengtao
 * @Description: zk servicew
 * @date 2018/12/26 11:48
 */
@Service
public class ZookeeperServiceImpl implements IZookeeperService {


    @Autowired
    private CuratorFramework client;

    @Override
    public String set(String path, Object object) throws Exception {
        String result;
        if(object != null){
            result = client.create().forPath(path, JsonHelper.obj2Json(object).getBytes("utf-8"));
        }else {
            result = client.create().forPath(path);
        }
        return result;
    }

    @Override
    public boolean isExists(String path) throws Exception {
        Stat stat = client.checkExists().forPath(path);
        if(stat != null){
            return true;
        }
        return false;
    }

    @Override
    public boolean remove(String path) throws Exception {
        client.delete().forPath(path);
        return true;
    }

    @Override
    public void test() throws Exception {
        /*client.getChildren().forPath("");
        byte[] content =  client.getData().forPath("");
        String source = new String(content,"utf-8");*/
        String path = "/brokers/ids";
        List<String> ids = getChildren(path);
        for (String id:ids){
            KafkaNode node = get(path+"/"+id,KafkaNode.class);
            System.out.println("host："+node);
        }
    }

    @Override
    public <T> T get(String path, Class<T> tClass) throws Exception {
        byte[] content = client.getData().forPath(path);
        if(content == null || content.length <= 0){
            return null;
        }
        String source = new String(content,"utf-8");
        T t = JsonHelper.json2Obj(source,tClass);
        return t;
    }

    @Override
    public List<String> getChildren(String path) throws Exception {
        return client.getChildren().forPath(path);
    }
}
